const Category = require('../../../models/blog_category');
const Article = require('../../../models/blog_article');
const ArticleCategory = require('../../../models/article_category_tags');
const Comment = require('../../../models/blog_comment');
const User = require('../../../models/blog_user'); // 前台用户
const AdminUser = require('../../../models/admin_users'); // 后台用户表
const Role = require('../../../models/admin_role'); // 后台角色
const Utils = require('../../../utils');
const authCodeFunc = require('../../../utils/authCode');
const UserOrRole = require('../../../models/admin_user_or_role'); // 后台用户角色关联表
const knex = require('../../../models/knex');

/**
 * 文章评论控制器
 */
const ControllerComment = {
    /* 获取分类 */
    getCategory: async function (req, res, next) {
        try {
            const list = await Category.all();

            res.json({ code: 200, data: { list } })
        } catch (e) {
            res.json({ code: 0, data: e })
        }
    },
    /* 获取文章 */
    getArticle: async function (req, res, next) {
        try {
            let { keywor } = req.query;
            let list = [];

            keywor = decodeURI(keywor); //* 对前端传递过来的信息进行解码

            const articles = await Article.all();

            articles.forEach((v) => {
                if (v.title.toLowerCase().indexOf(keywor.toLowerCase()) >= 0) {
                    list.push(v)
                }
            })

            res.json({ code: 200, msg: '链接成功', data: { list } })
        } catch (e) {
            res.json({ code: 0, data: e })
        }
    },
    /* 获取列表 */
    getList: async function (req, res, next) {
        try {
            let { per_page, page, keywor, category_id } = req.query;
            let users = User.table;
            let adUser = AdminUser.table;
            let roles = Role.table;
            let comments = Comment.table;
            let articles = Article.table;
            let or = ArticleCategory.table;
            let categorys = Category.table;
            let ac = '';

            if (category_id) ac = `${or}.category_id = ${category_id}`; // 分类搜索
            if (keywor) ac = `${or}.article_id = ${keywor}`; // 文章标题搜索

            // 后台管理用户联表查询
            let admin = await knex(comments)
                .join(adUser, `${comments}.user_id`, `${adUser}.id`)
                .join(roles, `${comments}.role`, `${roles}.id`)
                .join(or, `${comments}.article_id`, `${or}.article_id`)
                .join(articles, `${comments}.article_id`, `${articles}.id`)
                .join(categorys, `${or}.category_id`, `${categorys}.id`)
                .select(
                    `${comments}.id`,
                    `${comments}.comment_level`,
                    `${comments}.parent_comment_id`,
                    `${comments}.reply_comment_id`,
                    `${comments}.content`,
                    `${comments}.role`,
                    `${comments}.host`,
                    `${comments}.user_id`,
                    `${comments}.created_time`,
                    `${adUser}.user_name`,
                    `${adUser}.user_account as account`,
                    `${adUser}.user_avatar_url as avatar`,
                    `${roles}.name as role_name`,
                    `${articles}.title as article_title`,
                    `${or}.category_id`,
                    `${categorys}.title as category_title`,
                )
                .whereRaw(ac)

            // 前台博客用户联表查询
            let web = await knex(comments)
                .join(users, `${comments}.user_id`, `${users}.id`)
                .join(or, `${comments}.article_id`, `${or}.article_id`)
                .join(articles, `${comments}.article_id`, `${articles}.id`)
                .join(categorys, `${or}.category_id`, `${categorys}.id`)
                .select(
                    `${comments}.id`,
                    `${comments}.comment_level`,
                    `${comments}.parent_comment_id`,
                    `${comments}.reply_comment_id`,
                    `${comments}.content`,
                    `${comments}.role`,
                    `${comments}.host`,
                    `${comments}.user_id`,
                    `${comments}.created_time`,
                    `${users}.name as user_name`,
                    `${users}.account`,
                    `${users}.avatar_url as avatar`,
                    `${articles}.title as article_title`,
                    `${or}.category_id`,
                    `${categorys}.title as category_title`,
                )
                .whereRaw(ac)

            // admin与web合并
            const newComment = admin.concat(web);

            // 按id升序排序
            newComment.sort((a, b) => {
                return a.id - b.id
            });

            const getComment = Utils.getData(newComment); // 树形数据处理索引0为一级，其他均为子级
            const commentData = Utils.getChildrenTree(getComment, getComment[0]); // 按父子关系处理分类
            const list = Utils.getPagination(commentData, per_page, page); // 数据分页展示

            let total = commentData.length; // 文章总数
            let number = Math.ceil(total / per_page); // 计算出信息总页数

            res.json({ code: 200, msg: '连接成功', data: { list, total, number } })
        } catch (e) {
            res.json({ code: 0, data: e })
        }
    },
    getById: async function (req, res, next) {
        try {
            let { id } = req.query;

            const comments = await Comment.select({ id });

            let article_id = comments[0].article_id; // 文章id
            let parent_id = comments[0].parent_comment_id; // 父评论id
            let reply_id = comments[0].reply_comment_id; // 被回复的评论id
            let user = '';

            if (comments[0].host == 0) user = await User.select({ id: comments[0].user_id });

            if (comments[0].host == 1) user = await AdminUser.select({ id: comments[0].user_id });

            comments[0].user_name = user[0].user_name ? user[0].user_name : user[0].account;

            // 有父评论
            if (parent_id) {
                const parent = await Comment.select({ id: parent_id });
                let parent_user = '';
                if (parent[0].host == 0) parent_user = await User.select({ id: parent[0].user_id });

                if (parent[0].host == 1) parent_user = await AdminUser.select({ id: parent[0].user_id });

                comments[0].parent_content = parent[0].content;
                comments[0].parent_user_name = parent_user[0].user_name ? parent_user[0].user_name : parent_user[0].account;
                comments[0].parent_host = parent[0].host;
                comments[0].parent_role = parent[0].role;
            }

            // 有被回复的评论
            if (reply_id) {
                const reply = await Comment.select({ id: reply_id });

                let reply_user = '';
                if (reply[0].host == 0) reply_user = await User.select({ id: reply[0].user_id });

                if (reply[0].host == 1) reply_user = await AdminUser.select({ id: reply[0].user_id });

                comments[0].reply_content = reply[0].content;
                comments[0].reply_user_name = reply_user[0].user_name ? reply_user[0].user_name : reply_user[0].account;
                comments[0].reply_host = reply[0].host;
                comments[0].reply_role = reply[0].role;
            }

            // 文章信息
            const or = await ArticleCategory.select({ article_id });
            const articles = await Article.select({ id: article_id });
            comments[0].category_id = or[0].category_id;
            comments[0].article_title = articles[0].title;

            res.json({ code: 200, msg: '链接成功', data: { list: comments } })

        } catch (e) {
            res.json({ code: 0, data: e })
        }
    },
    Insert: async function (req, res, next) {
        try {
            // let { id, content } = req.body;
            // let authorization = req.headers.authorization;
            // let tokens = authorization.split(' ');
            // let user_decode = authCodeFunc(tokens[1], 'DECODE');
            // let user_info = user_decode.str.split('\t');
            // let admin_user_id = user_info[0]; // 后台管理用户id
            // let host = 1;
            // let comment_level = 2;
            // let params = {
            //     host,
            //     content,
            //     comment_level,
            //     user_id: admin_user_id,
            //     created_time: new Date().getTime()
            // }

            // const comment = await Comment.select({ id });

            // let article_id = comment[0].article_id;
            // let user_id = comment[0].user_id;
            // let parent_comment_id = comment[0].parent_comment_id;
            // let parent_comment_user_id = comment[0].parent_comment_user_id;
            // let parent_comment_user_host = comment[0].parent_comment_user_host;

            // if (parent_comment_id && parent_comment_user_id) {
            //     params.parent_comment_id = parent_comment_id;
            //     params.parent_comment_user_id = parent_comment_user_id;
            //     params.parent_comment_user_host = parent_comment_user_host;
            //     params.reply_comment_id = id;
            //     params.reply_comment_user_id = user_id;
            //     params.reply_comment_user_host = comment[0].host;
            // } else {
            //     params.parent_comment_id = id;
            //     params.parent_comment_user_id = user_id;
            //     params.parent_comment_user_host = comment[0].host;
            //     params.reply_comment_id = id;
            //     params.reply_comment_user_id = user_id;
            //     params.reply_comment_user_host = comment[0].host;
            // }
            // params.article_id = article_id;

            // await Comment.insert(params);

            res.json({ code: 200, msg: '回复成功', data: {} })
        } catch (e) {
            res.json({ code: 0, data: e })
        }
    },
    /* 删除 */
    del: async function (req, res, next) {
        try {
            let { id } = req.body;

            const comments = await Comment.select({ parent_comment_id: id })
            let comment_ids = comments.map(v => v.id);
            comment_ids.push(id)

            await Comment.batchDel(comment_ids)

            res.json({ code: 200, msg: '成功删除', data: {} })
        } catch (e) {
            res.json({ code: 0, data: e })
        }
    },
    /* 回复 */
    reply: async function (req, res, next) {
        try {
            let { id, content, comment_level } = req.body;
            let authorization = req.headers.authorization;
            let user_id = '';
            let host = 1;
            let parent_comment_id = ""

            if (authorization) {
                let token = authorization.split(' ');
                let user_decode = authCodeFunc(token[1], 'DECODE');
                let user_info = user_decode.str.split('\t');
                user_id = user_info[0];
            }

            const role = await UserOrRole.select({ user_id });
            const comments = await Comment.select({ id });

            if (comments[0].parent_comment_id) {
                parent_comment_id = comments[0].parent_comment_id; // 父留言id
            } else {
                parent_comment_id = id;
            }

            let reply_comment_id = id;

            let params = {
                user_id,
                content:encodeURI(content),
                comment_level,
                article_id: comments[0].article_id,
                host,
                parent_comment_id,
                reply_comment_id,
                role: role[0].role_id,
                created_time: new Date().getTime()
            }

            await Comment.insert(params);

            res.json({ code: 200, msg: '成功回复留言', data: {} })
        } catch (e) {
            res.json({ code: 0, data: e })
        }
    },
}

module.exports = ControllerComment;